package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-bean/vo"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type ISystemStoreRepository interface {
	Create(db *gorm.DB, systemStore *model.SystemStore) error
	FindPage(db *gorm.DB, params *pagehelper.Params) ([]*vo.SystemStoreVO, error)
	Count(db *gorm.DB, params *pagehelper.Params) (int64, error)
	FindStatistic(db *gorm.DB) ([]*vo.SystemStoreStatisticVO, error)
	Updates(db *gorm.DB, systemStore *model.SystemStore) error
	UpdateStatus(db *gorm.DB, ids []uint, status uint8) error
	BatchDelete(db *gorm.DB, ids []uint) error
}

type SystemStoreRepository struct {
}

func NewSystemStoreRepository() ISystemStoreRepository {
	return &SystemStoreRepository{}
}

func (*SystemStoreRepository) FindPage(db *gorm.DB, params *pagehelper.Params) (page []*vo.SystemStoreVO, err error) {
	tx := queryWrapper.ReuseWherePair(leftSystemStorePage(db), params.WherePair).
		Scopes(pagehelper.Paginate(params.Current, params.Size))
	return page, queryWrapper.ReuseOrderPair(tx, params.OrderPair).Find(&page).Error
}

func leftSystemStorePage(db *gorm.DB) *gorm.DB {
	return db.Table("`tz_system_store` tss").
		Select(`
			tss.*,
			ta.att_dir as att_dir,
			ta.att_id as att_id,
			ta.name as att_name,
			ta.image_type AS image_type,
			ta.NAME AS path
		`).Joins("LEFT JOIN tz_attachment ta ON tss.image = ta.att_id")
}

/*
SELECT
	tss.id,
	tss.`name`,
	tss.phone,
	tss.day_time,
	tss.`status`,
	tss.detailed_address,
	ta.att_dir,
	ta.image_type,
	ta.att_id,
	ta.`name` att_name
FROM
	`tz_system_store` tss
	LEFT JOIN tz_attachment ta ON tss.image = ta.att_id
WHERE
	tss.STATUS = 1
ORDER BY
	tss.updated_at,
	tss.created_at
	LIMIT 10
*/

func (*SystemStoreRepository) Count(db *gorm.DB, params *pagehelper.Params) (count int64, err error) {
	tx := queryWrapper.ReuseSelect(db.Table("tz_system_store as tss"), params.SelectFields)
	return count, queryWrapper.ReuseWherePair(tx, params.WherePair).Count(&count).Error
}

func (*SystemStoreRepository) Create(db *gorm.DB, systemStore *model.SystemStore) error {
	return db.Create(&systemStore).Error
}

func (*SystemStoreRepository) FindStatistic(db *gorm.DB) (voList []*vo.SystemStoreStatisticVO, err error) {
	return voList, db.Model(&model.SystemStore{}).Select("`status`", "count( id ) as total").Group("`status`").Find(&voList).Error
}

func (*SystemStoreRepository) Updates(db *gorm.DB, systemStore *model.SystemStore) error {
	return db.Model(&model.SystemStore{}).Where("id = ?", systemStore.Id).Updates(&systemStore).Error
}

func (*SystemStoreRepository) UpdateStatus(db *gorm.DB, ids []uint, status uint8) error {
	return db.Model(&model.SystemStore{}).Where("id in ?", ids).Update("status", status).Error
}

func (*SystemStoreRepository) BatchDelete(db *gorm.DB, ids []uint) error {
	return db.Delete(&model.SystemStore{}, ids).Error
}
